<template>
  <div class="login">
    <!-- 
          el-form 表单输入
          model	表单数据对象	object
          验证规则：Form 组件提供了表单验证的功能，只需要通过 rules 属性传入约定的验证规则，并将 Form-Item 的 prop 属性设置为需校验的字段名即可
          rules	表单验证规则	object
          validate	对整个表单进行校验的方法，参数为一个回调函数。该回调函数会在校验结束后被调用，并传入两个参数：是否校验成功和未通过校验的字段。若不传入回调函数，则会返回一个 promise
       -->
    <el-form
      :model="userinfo"
      :rules="rules"
      label-width="100px"
      class="loginInfo"
      ref="loginInfo"
    >
      <el-form-item prop="username" label="用户名">
        <el-input v-model="userinfo.username" clearable></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="userinfo.password" show-password clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//引入封装的登录接口
import { userLogin } from "../request/api";
import {mapActions} from 'vuex'
export default {
  data() {
    return {
      //输入项
      userinfo: {
        username: "",
        password: "",
      },
      //验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 6 到 16个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    ...mapActions(['changeUser']),
    //封装一个登录事件
    login() {
      this.$refs.loginInfo.validate((val) => {
        if (val) {
          console.log(this.userinfo, "表单对象");
          userLogin(this.userinfo)
          .then(res=>{
            if(res.code==200){
            console.log(res,"登录响应");
            this.$message.success(res.msg);
            //把登录结果储存到vuex中
            this.changeUser(res.list)
            //验证成功跳转到index界面
            this.$router.push("/index");
            }else{
              this.$message.error(res.msg);
            }
          })
        } else {
          console.log("验证失败");
        }
      });
    },
  },
};
</script>

<style scoped>
.login {
  width: 100%;
  height: 100vh;
  background: #ccc;
}
.loginInfo {
  width: 400px;
  height: 300px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -150px 0 0 -175px;
}
</style>
